<!--
 * @Author: hpc(hepch)
 * @Date: 2021-06-04 12:47:39
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-10-03 21:42:36
 * @Description:展示POI
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div id="SearchResult">
    <a-card
      class="result-card-list"
      title="结果展示"
      v-if="listvisible"
      size="small"
    >
      <!-- <a-select
        slot="extra"
        size="small"
        v-show="false"
        style="margin-right: 10px; width: 100px"
        v-model="selectPoiCategory"
        @change="showAcategoryPoi"
        ><a-select-option value="all">显示所有</a-select-option>
        <a-select-option v-for="item in PoiCategory" :key="item.poicode">
          {{ item.FLNAME }}
        </a-select-option>
      </a-select> -->
      <a-button
        type="link"
        slot="extra"
        :icon="sortIcon"
        v-show="visiable"
        @click="isSort()"
        title="排序"
      ></a-button>
      <!-- <a-button
        type="link"
        slot="extra"
        :icon="icon"
        @click="isExpend()"
      ></a-button> -->
      <a-button
        type="link"
        slot="extra"
        icon="close"
        @click="onClose()"
      ></a-button>
      <a-spin tip="正在查询......" v-show="loading">
        <div class="spin-content"></div>
      </a-spin>
      <a-list
        v-show="!loading"
        class="poi_list"
        item-layout="horizontal"
        :data-source="hits"
        :pagination="pagination"
        :style="getExpendHeight"
      >
        <a-list-item slot="renderItem" slot-scope="hit, index">
          <div>
            <a style="display: inline" @click="checkIcon(hit, index)"
              ><icon-font type="icon-weizhi" /></a
            >&nbsp;
            <a style="display: inline" @click="checkPOI(hit, index)">
              <!-- <icon-font type="icon-weizhi" />&nbsp; -->{{ index + 1 }}.{{
                hit._source.NAME
              }}</a
            >
            <br />
            <span style="margin-left: 18px">
              {{ hit._source.ADDRESS ? hit._source.ADDRESS : "无地址信息" }}
            </span>
          </div>
        </a-list-item>
      </a-list>
    </a-card>
    <a-card
      class="poi-card"
      :title="poiName"
      style="width: 300px"
      v-if="poivisible"
      size="small"
    >
      <a-button slot="extra" type="link" icon="left" @click="back()"></a-button>
      <a-card class="infocard" size="small">
        <h3 class="poiName-title">{{ poiName }}</h3>
        <div class="info-content">
          <a-row v-for="(item, index) in poiPoint" :key="index">
            <a-col :span="8" style="text-align: left">
              <span style="margin-left: 16px">{{ item.filedname }}</span>
            </a-col>
            <a-col :span="16">
              <span>{{ item.value }}</span>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </a-card>
  </div>
</template>

<script>
import L from "leaflet";
import { esPost } from "@/services/ES/esQuery";
import queryMixins from "../../mixins/queryMixins";
import localStorage from "@/utils/localStorage";
import { filedskeyValue } from "@/utils/poiFiledsCn";
import { esHitsjsonSortByField } from "@/utils/sortjson";
import { reEsgroup } from "@/utils/regroup";
// 自定义图标
import { Icon } from "ant-design-vue";
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: "./iconfont/iconfont.js",
});
export default {
  data() {
    return {
      listvisible: false,
      poivisible: false,
      visiable: true,
      loading: true,
      isExpendlist: false,
      icon: "down",
      sortIcon: "caret-up",
      inputStr: "",
      groupStr: "",
      hits: [],
      selectPoiCategory: "all",
      markers: [],
      pagination: {
        showLessItems: true,
        onChange: (page) => {
          this.onPageChange(page);
          this.currentPage = page;
          this.pagination.current = page;
        },
        pageSize: 10,
        defaultCurrent: 1,
        total: 100,
        size: "small",
      },
      currentPage: 1,
      SearchDictionary: JSON.parse(localStorage.get("SearchDictionary")),
    };
  },

  mixins: [queryMixins],
  components: { IconFont },
  computed: {
    map() {
      return this.$store.state.map;
    },
    //查询图标图层
    markersFeatureGroup() {
      return this.$store.state.markersFeatureGroup;
    },
    PoiCategory() {
      return this.$store.state.config.PoiCategory;
    },
  },
  methods: {
    regroupInEShits(arr, str) {
      var map = {},
        dest = [];
      arr.map((item) => {
        if (!map[item._source[str]]) {
          dest.push({
            name: item._source[str],
            data: [item],
          });
          map[item._source[str]] = item;
        } else {
          dest
            .filter((itemD) => itemD.name == item._source[str])[0]
            .data.push(item);
        }
      });
      return dest;
    },

    async getEShits() {
      this.poivisible = false;
      this.loading = true;
      const querydata = this.buildESqueryData(
        this.inputStr,
        this.groupStr,
        0,
        100
      );
      const querydataByCutWord = this.buildESqueryDataByCutWord(
        this.inputStr,
        this.groupStr,
        0,
        100
      );
      const esRes = await esPost(this.defaultSearchURL, querydata);
      const esResByCutWord = await esPost(
        this.cutWordSearchURL,
        querydataByCutWord
      );
      this.loading = false;
      let doubleSearchits = esRes.hits.hits.concat(esResByCutWord.hits.hits);
      let afterReGroupList = this.regroupInEShits(doubleSearchits, "NAME");
      let hits = [];
      afterReGroupList.map((item) => {
        hits.push(item.data[0]);
      });
      this.hits = hits;
      //console.log("this.hits", this.hits);
      this.pagination.total = this.hits.length;
      this.hits.map((item) => {
        let sort = item._source.NAME.indexOf(this.$parent.inputStr);
        item._source.sortChineseName =
          sort >= 0 ? (sort == this.$parent.inputStr ? sort : sort + 1) : 101;
      });
      this.hits = esHitsjsonSortByField(this.hits, "POI_FLAG");
      this.hitsdata = reEsgroup(this.hits, "POI_FLAG");
      this.hits = [];
      this.hitsdata.map((item) => {
        item.data = esHitsjsonSortByField(item.data, "Importance");
        item.data.map((item) => {
          this.hits.push(item);
        });
      });
      this.hits = esHitsjsonSortByField(this.hits, "sortChineseName");
      console.log("查询到的数据", this.hits);
      this.initial = this.hits;
      if (this.hits.length == 0) {
        this.$message.info("未查询到相关数据，请检查输入关键词");
        return;
      }
      this.hits.length >= 10
        ? this.addMarkers(this.hits.slice(0, 10))
        : this.addMarkers(this.hits.slice(0, this.hits.length));
    },
    back() {
      this.poivisible = false;
      this.listvisible = true;
      this.pagination.current = this.currentPage;
    },
    isExpend() {
      this.isExpendlist = !this.isExpendlist;
      this.icon == "down" ? (this.icon = "up") : (this.icon = "down");
    },
    getExpendHeight() {
      let style = {
        height: "0px",
        overflow: "hidden",
      };

      return style;
    },
    //排序
    isSort() {
      //更换图标
      this.sortIcon == "caret-up"
        ? (this.sortIcon = "caret-down")
        : (this.sortIcon = "caret-up");
      this.dataSort();
    },
    dataSort() {
      //直接反序
      this.hits = this.hits.reverse();
      this.addMarkers(this.hits.slice(0, 10));
    },
    getClassfeaturenInfo(key, item) {
      // 匹配字典表
      let cname = key;
      for (let dict of this.SearchDictionary) {
        if (dict.ename.toUpperCase() == key.toUpperCase()) {
          cname = dict.cname;
          if (item[key] && item[key] != "") {
            this.poiPoint.push({
              filedname: cname,
              value: item[key],
            });
          }
        }
      }
    },
    showpoiNameCN(key) {
      // 匹配字典表
      let cname = key;
      for (let dict of this.SearchDictionary) {
        if (dict.ename.toUpperCase() == key.toUpperCase()) {
          cname = dict.cname;
          return cname;
        }
      }
      return false;
    },
    getPoiInfo(hit) {
      this.poiName = hit._source.NAME;
      this.poiPoint = [];
      const item = hit._source;
      for (let key in item) {
        if (!key.startsWith("Sm")) {
          if (item[key] && key != item.searchFiledName) {
            this.isSearchByclass
              ? this.getClassfeaturenInfo(key, item)
              : this.pointInfo(key, item[key]);
          }
        }
      }
    },
    pointInfo(key, value) {
      let keycn = filedskeyValue(key);
      if (keycn) {
        this.poiPoint.push({
          filedname: keycn,
          value: value,
        });
      }
    },
    addMarkers(hits) {
      if (!hits.length) return;
      let zIndexOffset = 10; //zIndexOffset图标叠加的顺序
      this.markersFeatureGroup.clearLayers();
      this.markers = [];
      hits.forEach((hit, index) => {
        const icon = L.icon({
          iconSize: [31, 39],
          iconAnchor: [15, 39],
          iconUrl: `./img/icons/${index + 1}_r.png`,
          popupAnchor: [0, -39],
          shadowUrl: "./img/icons/marker-shadow.png",
          shadowSize: [31, 39],
          shadowAnchor: [8, 39],
        });
        let latlng = [hit._source.location.lat, hit._source.location.lon];

        let marker = L.marker(latlng, {
          icon: icon,
          zIndexOffset: zIndexOffset,
        });
        let content = `名称
          ：${hit._source.NAME}`;
        marker.bindPopup(content, { closeButton: false });
        marker.on("click", () => {
          this.listvisible = false;
          this.poivisible = false;
          this.getPoiInfo(hit);
          this.poivisible = true;
        });
        marker.addTo(this.markersFeatureGroup);
        this.markers.push(marker);
        zIndexOffset--;
      });
      this.map.flyToBounds(this.markersFeatureGroup.getBounds());
    },
    checkPOI(hit, index) {
      //遍历一次初始化zIndexOffset
      for (var i = 0; i < this.markers.length; i++) {
        this.markers[i].setZIndexOffset(10 - i);
      }
      const latlng = [hit._source.location.lat, hit._source.location.lon];
      this.map.setView(latlng, 17);
      this.getPoiInfo(hit);
      this.markers[index].setZIndexOffset(20);
      this.markers[index].openPopup();
      this.listvisible = false;
      this.poivisible = true;
    },
    checkIcon(hit, index) {
      //遍历一次初始化zIndexOffset
      for (var i = 0; i < this.markers.length; i++) {
        this.markers[i].setZIndexOffset(10 - i);
      }
      const latlng = [hit._source.location.lat, hit._source.location.lon];
      this.map.setView(latlng, 17);
      this.markers[index].setZIndexOffset(20);
      this.markers[index].openPopup();
      this.listvisible = true;
    },
    async onPageChange(page) {
      this.addMarkers(this.hits.slice((page - 1) * 10, page * 10));
    },
    onClose() {
      this.listvisible = false;
      this.poivisible = false;
      this.loading = true;
      this.hits = [];
      this.markers = [];
      this.markersFeatureGroup.clearLayers();
    },
    showAcategoryPoi(value) {
      this.selectPoiCategory = value;
      if (this.selectPoiCategory == "all") {
        this.hits = this.initial;
      } else {
        this.initial.length
          ? (this.hits = this.initial.filter(
              (item) => item._source.KIND.indexOf(this.selectPoiCategory) > -1
            ))
          : "";
      }
      this.pagination.total = this.hits.length;
      this.hits.length >= 10
        ? this.addMarkers(this.hits.slice(0, 10))
        : this.addMarkers(this.hits.slice(0, this.hits.length));
    },
  },
};
</script>

<style lang="less" scoped>
#SearchResult {
  border-radius: 5px;
  position: absolute;
  top: 74px;
  left: 20px;
  z-index: 999;

  .result-card-list {
    margin-top: 2px;
    width: 300px !important;
    .poi_list {
      padding: 0 0px;
      padding-left: 10px;
      padding-right: 0px;
      // height: 700px;
      overflow: hidden;
      .ant-list-item {
        padding: 12px 0 3px 0;
        span {
          font-size: 12px;
        }
        a,
        span {
          display: inline-block;
          width: 240px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .spin-content {
      min-height: 700px;
      border: 1px solid #91d5ff;
      background-color: #e6f7ff;
      padding: 30px;
    }
  }
  .poi-card {
    margin-top: 2px;
    width: 300px !important;
    /deep/.ant-row {
      border-bottom: 1px solid #e8e8e8;
    }
    .ant-card-body {
      .infocard {
        .info-content {
          max-width: 400px;
          max-height: 350px;
          overflow: auto;
          text-overflow: ellipsis;
        }
        border: none;
        .poiName-title {
          max-width: 80%;
          text-align: center;
        }
      }
    }
  }
}
</style>
